import 'dart:convert';
import 'package:encrypt/encrypt.dart' hide SecureRandom;
import 'package:flutter/foundation.dart' hide Key;
import 'package:pointycastle/export.dart';
import 'package:pointycastle/pointycastle.dart';

/// RSA 加密工具类
class RSAUtil {
  /// 生成 RSA 密钥对
  static Map<String, String> generateKeyPair({int keySize = 2048}) {
    try {
      final secureRandom = FortunaRandom();
      final random = Uint8List(32);
      final rnd = SecureRandom('Fortuna')..seed(KeyParameter(random));
      secureRandom.seed(KeyParameter(random));

      final keyGenerator = RSAKeyGenerator()
        ..init(ParametersWithRandom(
          RSAKeyGeneratorParameters(BigInt.parse('65537'), keySize, 64),
          rnd,
        ));

      final keyPair = keyGenerator.generateKeyPair();

      return {
        'publicKey': _publicKeyToPem(keyPair.publicKey as RSAPublicKey),
        'privateKey': _privateKeyToPem(keyPair.privateKey as RSAPrivateKey),
      };
    } catch (e) {
      debugPrint('生成密钥对错误: $e');
      return {};
    }
  }

  /// 从PEM格式公钥解析RSA公钥
  static RSAPublicKey? parsePublicKeyFromPem(String pem) {
    try {
      final parser = RSAKeyParser();
      return parser.parse(pem) as RSAPublicKey;
    } catch (e) {
      debugPrint('解析公钥错误: $e');
      return null;
    }
  }

  /// 从PEM格式私钥解析RSA私钥
  static RSAPrivateKey? parsePrivateKeyFromPem(String pem) {
    try {
      final parser = RSAKeyParser();
      return parser.parse(pem) as RSAPrivateKey;
    } catch (e) {
      debugPrint('解析私钥错误: $e');
      return null;
    }
  }

  /// 公钥转PEM格式
  static String _publicKeyToPem(RSAPublicKey publicKey) {
    final publicKeySeq = ASN1Sequence()
      ..add(ASN1Integer(publicKey.modulus))
      ..add(ASN1Integer(publicKey.exponent));

    final publicKeyBitString =
        ASN1BitString(stringValues: publicKeySeq.encode());

    final topLevelSeq = ASN1Sequence()
      ..add(ASN1ObjectIdentifier.fromName('rsaEncryption'))
      ..add(ASN1Null())
      ..add(publicKeyBitString);

    final data = base64.encode(topLevelSeq.encode());

    // 格式化PEM
    final pem = StringBuffer()..write('-----BEGIN PUBLIC KEY-----\n');

    for (var i = 0; i < data.length; i += 64) {
      final end = i + 64;
      pem.write(data.substring(i, end < data.length ? end : data.length));
      pem.write('\n');
    }

    pem.write('-----END PUBLIC KEY-----');
    return pem.toString();
  }

  /// 私钥转PEM格式
  static String _privateKeyToPem(RSAPrivateKey privateKey) {
    final privateKeySeq = ASN1Sequence()
      ..add(ASN1Integer(BigInt.zero))
      ..add(ASN1Integer(privateKey.modulus))
      ..add(ASN1Integer(BigInt.parse('65537'))) // 使用固定的公钥指数
      ..add(ASN1Integer(privateKey.privateExponent))
      ..add(ASN1Integer(privateKey.p))
      ..add(ASN1Integer(privateKey.q));

    final topLevelSeq = ASN1Sequence()
      ..add(ASN1Integer(BigInt.zero))
      ..add(ASN1ObjectIdentifier.fromName('rsaEncryption'))
      ..add(ASN1OctetString(octets: privateKeySeq.encode()));

    final data = base64.encode(topLevelSeq.encode());

    // 格式化PEM
    final pem = StringBuffer()..write('-----BEGIN PRIVATE KEY-----\n');

    for (var i = 0; i < data.length; i += 64) {
      final end = i + 64;
      pem.write(data.substring(i, end < data.length ? end : data.length));
      pem.write('\n');
    }

    pem.write('-----END PRIVATE KEY-----');
    return pem.toString();
  }

  /// 公钥加密
  static String? encryptWithPublicKey(String plainText, String publicKeyPem) {
    try {
      final publicKey = parsePublicKeyFromPem(publicKeyPem);
      if (publicKey == null) return null;

      final encrypter = Encrypter(RSA(publicKey: publicKey));
      final encrypted = encrypter.encrypt(plainText);
      return encrypted.base64;
    } catch (e) {
      debugPrint('公钥加密错误: $e');
      return null;
    }
  }

  /// 私钥解密
  static String? decryptWithPrivateKey(
      String cipherText, String privateKeyPem) {
    try {
      final privateKey = parsePrivateKeyFromPem(privateKeyPem);
      if (privateKey == null) return null;

      final encrypter = Encrypter(RSA(privateKey: privateKey));
      final encrypted = Encrypted.fromBase64(cipherText);
      final decrypted = encrypter.decrypt(encrypted);
      return decrypted;
    } catch (e) {
      debugPrint('私钥解密错误: $e');
      return null;
    }
  }

  /// 私钥签名
  static String? signWithPrivateKey(String plainText, String privateKeyPem) {
    try {
      final privateKey = parsePrivateKeyFromPem(privateKeyPem);
      if (privateKey == null) return null;

      final encrypter = Encrypter(RSA(privateKey: privateKey));
      final encrypted = encrypter.encrypt(plainText);
      return encrypted.base64;
    } catch (e) {
      debugPrint('签名错误: $e');
      return null;
    }
  }

  /// 公钥验证签名
  static bool verifyWithPublicKey(
      String plainText, String signature, String publicKeyPem) {
    try {
      final publicKey = parsePublicKeyFromPem(publicKeyPem);
      if (publicKey == null) return false;

      final encrypter = Encrypter(RSA(publicKey: publicKey));
      final encrypted = Encrypted.fromBase64(signature);
      final decrypted = encrypter.decrypt(encrypted);
      return decrypted == plainText;
    } catch (e) {
      debugPrint('验证签名错误: $e');
      return false;
    }
  }

  // ========== 对应 OC 中的方法 ==========

  /// Base64 编码数据
  static String base64EncodeData(Uint8List data) {
    return base64.encode(data);
  }

  /// Base64 解码字符串
  static Uint8List? base64Decode(String str) {
    try {
      return base64.decode(str);
    } catch (e) {
      debugPrint('Base64解码错误: $e');
      debugPrint('输入字符串: $str');
      return null;
    }
  }

  /// Base64 解码字符串为字符串
  static String? base64DecodeStr(String str) {
    try {
      final data = base64.decode(str);
      return utf8.decode(data);
    } catch (e) {
      debugPrint('Base64解码字符串错误: $e');
      debugPrint('输入字符串: $str');
      return null;
    }
  }

  /// 移除公钥头部（对应 OC 中的 stripPublicKeyHeader）
  static Uint8List? stripPublicKeyHeader(Uint8List dKey) {
    if (dKey.isEmpty) return null;

    int idx = 0;
    if (dKey[idx++] != 0x30) return null;

    if (dKey[idx] > 0x80) {
      idx += dKey[idx] - 0x80 + 1;
    } else {
      idx++;
    }

    // PKCS #1 rsaEncryption szOID_RSA_RSA
    final seqiod = [
      0x30,
      0x0d,
      0x06,
      0x09,
      0x2a,
      0x86,
      0x48,
      0x86,
      0xf7,
      0x0d,
      0x01,
      0x01,
      0x01,
      0x05,
      0x00
    ];
    for (int i = 0; i < seqiod.length; i++) {
      if (idx + i >= dKey.length || dKey[idx + i] != seqiod[i]) {
        return null;
      }
    }
    idx += seqiod.length;

    if (dKey[idx++] != 0x03) return null;

    if (dKey[idx] > 0x80) {
      idx += dKey[idx] - 0x80 + 1;
    } else {
      idx++;
    }

    if (dKey[idx++] != 0x00) return null;

    return dKey.sublist(idx);
  }

  /// 移除私钥头部（对应 OC 中的 stripPrivateKeyHeader）
  static Uint8List? stripPrivateKeyHeader(Uint8List dKey) {
    if (dKey.isEmpty) {
      debugPrint('私钥数据为空');
      return null;
    }

    debugPrint('私钥数据长度: ${dKey.length}');

    int idx = 22; // magic byte at offset 22
    if (idx >= dKey.length) {
      debugPrint('索引超出范围: idx=$idx, length=${dKey.length}');
      return null;
    }

    if (dKey[idx++] != 0x04) {
      debugPrint('在偏移22处未找到0x04字节，实际值: 0x${dKey[idx-1].toRadixString(16)}');
      return null;
    }

    // calculate length of the key
    int cLen = dKey[idx++];
    bool det = (cLen & 0x80) != 0;

    debugPrint('长度字节: 0x${cLen.toRadixString(16)}, det: $det');

    if (!det) {
      cLen = cLen & 0x7f;
      debugPrint('短格式长度: $cLen');
    } else {
      int byteCount = cLen & 0x7f;
      debugPrint('长格式长度，字节数: $byteCount');
      
      if (byteCount + idx > dKey.length) {
        debugPrint('长度字段超出缓冲区: byteCount=$byteCount, idx=$idx, length=${dKey.length}');
        return null;
      }
      
      int accum = 0;
      for (int i = 0; i < byteCount; i++) {
        accum = (accum << 8) + dKey[idx + i];
      }
      idx += byteCount;
      cLen = accum;
      debugPrint('计算出的长度: $cLen');
    }

    if (idx + cLen > dKey.length) {
      debugPrint('数据长度超出缓冲区: idx=$idx, cLen=$cLen, length=${dKey.length}');
      return null;
    }

    debugPrint('成功移除头部，返回数据长度: $cLen');
    return dKey.sublist(idx, idx + cLen);
  }

  /// 添加公钥（对应 OC 中的 addPublicKey）
  static RSAPublicKey? addPublicKey(String key) {
    try {
      // 清理 PEM 格式
      String cleanedKey = key;
      if (cleanedKey.contains('-----BEGIN PUBLIC KEY-----') &&
          cleanedKey.contains('-----END PUBLIC KEY-----')) {
        final startIndex = cleanedKey.indexOf('-----BEGIN PUBLIC KEY-----') +
            '-----BEGIN PUBLIC KEY-----'.length;
        final endIndex = cleanedKey.indexOf('-----END PUBLIC KEY-----');
        cleanedKey = cleanedKey.substring(startIndex, endIndex);
      }

      cleanedKey = cleanedKey.replaceAll(RegExp(r'\s+'), '');

      // Base64 解码
      final data = base64Decode(cleanedKey);
      if (data == null) return null;

      // 移除头部
      final strippedData = stripPublicKeyHeader(data);
      if (strippedData == null) return null;

      // 解析 ASN.1
      final asn1Parser = ASN1Parser(strippedData);
      final publicKeySeq = asn1Parser.nextObject() as ASN1Sequence;

      final modulus = (publicKeySeq.elements![0] as ASN1Integer).integer!;
      final exponent = (publicKeySeq.elements![1] as ASN1Integer).integer!;

      return RSAPublicKey(modulus, exponent);
    } catch (e) {
      debugPrint('添加公钥错误: $e');
      return null;
    }
  }

  /// 添加私钥（对应 OC 中的 addPrivateKey）
  static RSAPrivateKey? addPrivateKey(String key) {
    try {
      // 首先尝试使用 encrypt 库的 RSAKeyParser
      final parser = RSAKeyParser();
      final result = parser.parse(key) as RSAPrivateKey;
      debugPrint('使用 RSAKeyParser 成功解析私钥');
      return result;
    } catch (e) {
      debugPrint('RSAKeyParser 解析失败: $e');
      debugPrint('尝试手动解析...');
      
      // 如果 RSAKeyParser 失败，尝试手动解析
      return _parsePrivateKeyManually(key);
    }
  }

  /// 手动解析私钥
  static RSAPrivateKey? _parsePrivateKeyManually(String key) {
    try {
      // 清理 PEM 格式
      String cleanedKey = key;
      if (cleanedKey.contains('-----BEGIN PRIVATE KEY-----') &&
          cleanedKey.contains('-----END PRIVATE KEY-----')) {
        final startIndex = cleanedKey.indexOf('-----BEGIN PRIVATE KEY-----') +
            '-----BEGIN PRIVATE KEY-----'.length;
        final endIndex = cleanedKey.indexOf('-----END PRIVATE KEY-----');
        cleanedKey = cleanedKey.substring(startIndex, endIndex);
      }

      cleanedKey = cleanedKey.replaceAll(RegExp(r'\s+'), '');

      // Base64 解码
      final data = base64Decode(cleanedKey);
      if (data == null) {
        debugPrint('Base64解码失败');
        return null;
      }

      // 尝试两种解析方式
      RSAPrivateKey? result = _parsePrivateKeyMethod1(data);
      if (result != null) {
        debugPrint('使用方法1成功解析私钥');
        return result;
      }

      result = _parsePrivateKeyMethod2(data);
      if (result != null) {
        debugPrint('使用方法2成功解析私钥');
        return result;
      }

      debugPrint('所有解析方法都失败');
      return null;
    } catch (e) {
      debugPrint('手动解析私钥错误: $e');
      return null;
    }
  }

  /// 解析私钥方法1：使用 stripPrivateKeyHeader
  static RSAPrivateKey? _parsePrivateKeyMethod1(Uint8List data) {
    try {
      // 移除头部
      final strippedData = stripPrivateKeyHeader(data);
      if (strippedData == null) {
        debugPrint('方法1: 移除私钥头部失败');
        return null;
      }

      debugPrint('方法1: 移除头部后的数据长度: ${strippedData.length}');

      // 解析 ASN.1
      final asn1Parser = ASN1Parser(strippedData);
      final privateKeySeq = asn1Parser.nextObject() as ASN1Sequence;

      debugPrint('方法1: 私钥序列元素数量: ${privateKeySeq.elements!.length}');

      // 检查元素数量
      if (privateKeySeq.elements!.length < 7) {
        debugPrint('方法1: 私钥序列元素数量不足: ${privateKeySeq.elements!.length}');
        return null;
      }

      final modulus = (privateKeySeq.elements![1] as ASN1Integer).integer!;
      final publicExponent = (privateKeySeq.elements![2] as ASN1Integer).integer!;
      final privateExponent =
          (privateKeySeq.elements![3] as ASN1Integer).integer!;
      final p = (privateKeySeq.elements![4] as ASN1Integer).integer!;
      final q = (privateKeySeq.elements![5] as ASN1Integer).integer!;
      final dP = (privateKeySeq.elements![6] as ASN1Integer).integer!;

      debugPrint('方法1: 解析出的参数 - modulus: ${modulus.bitLength}位, publicExponent: $publicExponent, privateExponent: ${privateExponent.bitLength}位');

      // 尝试使用 encrypt 库的 RSAPrivateKey 构造函数
      try {
        return RSAPrivateKey(modulus, privateExponent, p, q, dP);
      } catch (e) {
        debugPrint('方法1: pointycastle RSAPrivateKey 构造失败: $e');
        // 如果失败，尝试使用 encrypt 库的构造函数
        try {
          // 注意：encrypt 库的 RSAPrivateKey 构造函数参数顺序可能不同
          return RSAPrivateKey(modulus, privateExponent, p, q, dP);
        } catch (e2) {
          debugPrint('方法1: encrypt RSAPrivateKey 构造也失败: $e2');
          return null;
        }
      }
    } catch (e) {
      debugPrint('方法1解析失败: $e');
      return null;
    }
  }

  /// 解析私钥方法2：直接解析完整的 ASN.1 结构
  static RSAPrivateKey? _parsePrivateKeyMethod2(Uint8List data) {
    try {
      debugPrint('方法2: 开始解析完整ASN.1结构，数据长度: ${data.length}');

      // 解析完整的 ASN.1 结构
      final asn1Parser = ASN1Parser(data);
      final topSeq = asn1Parser.nextObject() as ASN1Sequence;

      debugPrint('方法2: 顶层序列元素数量: ${topSeq.elements!.length}');

      // 处理 PKCS#8 格式
      ASN1Sequence privateKeySeq;
      if (topSeq.elements!.length == 3) {
        // PKCS#8 格式
        final privateKeyOctet = topSeq.elements![2] as ASN1OctetString;
        final privateKeyParser = ASN1Parser(privateKeyOctet.valueBytes!);
        privateKeySeq = privateKeyParser.nextObject() as ASN1Sequence;
        debugPrint('方法2: 使用PKCS#8格式');
      } else {
        // PKCS#1 格式
        privateKeySeq = topSeq;
        debugPrint('方法2: 使用PKCS#1格式');
      }

      debugPrint('方法2: 私钥序列元素数量: ${privateKeySeq.elements!.length}');

      // 检查元素数量
      if (privateKeySeq.elements!.length < 7) {
        debugPrint('方法2: 私钥序列元素数量不足: ${privateKeySeq.elements!.length}');
        return null;
      }

      final modulus = (privateKeySeq.elements![1] as ASN1Integer).integer!;
      final publicExponent = (privateKeySeq.elements![2] as ASN1Integer).integer!;
      final privateExponent =
          (privateKeySeq.elements![3] as ASN1Integer).integer!;
      final p = (privateKeySeq.elements![4] as ASN1Integer).integer!;
      final q = (privateKeySeq.elements![5] as ASN1Integer).integer!;
      final dP = (privateKeySeq.elements![6] as ASN1Integer).integer!;

      debugPrint('方法2: 解析出的参数 - modulus: ${modulus.bitLength}位, publicExponent: $publicExponent, privateExponent: ${privateExponent.bitLength}位');

      // 尝试使用 encrypt 库的 RSAPrivateKey 构造函数
      try {
        return RSAPrivateKey(modulus, privateExponent, p, q, dP);
      } catch (e) {
        debugPrint('方法2: pointycastle RSAPrivateKey 构造失败: $e');
        // 如果失败，尝试使用 encrypt 库的构造函数
        try {
          // 注意：encrypt 库的 RSAPrivateKey 构造函数参数顺序可能不同
          return RSAPrivateKey(modulus, privateExponent, p, q, dP);
        } catch (e2) {
          debugPrint('方法2: encrypt RSAPrivateKey 构造也失败: $e2');
          return null;
        }
      }
    } catch (e) {
      debugPrint('方法2解析失败: $e');
      return null;
    }
  }

  /// 使用私钥加密数据（对应 OC 中的 encryptData:privateKey:）
  static Uint8List? encryptDataWithPrivateKey(
      Uint8List data, String privateKey) {
    if (data.isEmpty || privateKey.isEmpty) return null;

    final keyRef = addPrivateKey(privateKey);
    if (keyRef == null) return null;

    return encryptDataWithKeyRef(data, keyRef);
  }

  /// 使用私钥加密字符串（对应 OC 中的 encryptString:privateKey:）
  static String? encryptStringWithPrivateKey(String str, String privateKey) {
    final data = encryptDataWithPrivateKey(utf8.encode(str), privateKey);
    if (data == null) return null;
    return base64EncodeData(data);
  }

  /// 使用私钥签名数据（对应 OC 中的 signData:privateKey:）
  static Uint8List? signDataWithPrivateKey(Uint8List data, String privateKey) {
    if (data.isEmpty || privateKey.isEmpty) return null;

    final keyRef = addPrivateKey(privateKey);
    if (keyRef == null) return null;

    return signDataWithKeyRef(data, keyRef);
  }

  /// 使用私钥签名字符串（对应 OC 中的 signString:privateKey:）
  static String? signStringWithPrivateKey(String str, String privateKey) {
    final data = signDataWithPrivateKey(utf8.encode(str), privateKey);
    if (data == null) return null;
    return base64EncodeData(data);
  }

  /// 使用私钥解密数据（对应 OC 中的 decryptData:privateKey:）
  static Uint8List? decryptDataWithPrivateKey(
      Uint8List data, String privateKey) {
    if (data.isEmpty || privateKey.isEmpty) return null;

    final keyRef = addPrivateKey(base64DecodeStr(privateKey) ?? privateKey);
    if (keyRef == null) return null;

    return decryptDataWithKeyRef(data, keyRef);
  }

  /// 使用私钥解密字符串（对应 OC 中的 decryptString:privateKey:）
  static String? decryptStringWithPrivateKey(String str, String privateKey) {
    final data = base64Decode(str);
    if (data == null) return null;

    final decryptedData = decryptDataWithPrivateKey(data, privateKey);
    if (decryptedData == null) return null;

    return utf8.decode(decryptedData);
  }

  /// 使用公钥加密数据（对应 OC 中的 encryptData:publicKey:）
  static Uint8List? encryptDataWithPublicKey(Uint8List data, String publicKey) {
    if (data.isEmpty || publicKey.isEmpty) return null;

    final keyRef = addPrivateKey(publicKey);
    if (keyRef == null) return null;

    return encryptDataWithKeyRef(data, keyRef);
  }

  /// 使用公钥加密字符串（对应 OC 中的 encryptString:publicKey:）
  static String? encryptStringWithPublicKey(String str, String publicKey) {
    final data = encryptDataWithPublicKey(utf8.encode(str), publicKey);
    if (data == null) return null;
    return base64EncodeData(data);
  }

  /// 使用公钥解密数据（对应 OC 中的 decryptData:publicKey:）
  static Uint8List? decryptDataWithPublicKey(Uint8List data, String publicKey) {
    if (data.isEmpty || publicKey.isEmpty) return null;

    final keyRef = addPrivateKey(publicKey);
    if (keyRef == null) return null;

    return decryptDataWithKeyRef(data, keyRef);
  }

  /// 使用公钥解密字符串（对应 OC 中的 decryptString:publicKey:）
  static String? decryptStringWithPublicKey(String str, String publicKey) {
    final data = base64Decode(str);
    if (data == null) return null;

    final decryptedData = decryptDataWithPublicKey(data, publicKey);
    if (decryptedData == null) return null;

    return utf8.decode(decryptedData);
  }

  // ========== 内部方法 ==========

  /// 使用密钥引用加密数据
  static Uint8List? encryptDataWithKeyRef(
      Uint8List data, RSAPrivateKey keyRef) {
    try {
      final encrypter = Encrypter(RSA(privateKey: keyRef));
      final encrypted = encrypter.encryptBytes(data);
      return Uint8List.fromList(encrypted.bytes);
    } catch (e) {
      debugPrint('使用密钥引用加密错误: $e');
      return null;
    }
  }

  /// 使用密钥引用签名数据
  static Uint8List? signDataWithKeyRef(Uint8List data, RSAPrivateKey keyRef) {
    try {
      final encrypter = Encrypter(RSA(privateKey: keyRef));
      final encrypted = encrypter.encryptBytes(data);
      return Uint8List.fromList(encrypted.bytes);
    } catch (e) {
      debugPrint('使用密钥引用签名错误: $e');
      return null;
    }
  }

  /// 使用密钥引用解密数据
  static Uint8List? decryptDataWithKeyRef(
      Uint8List data, RSAPrivateKey keyRef) {
    try {
      final encrypter = Encrypter(RSA(privateKey: keyRef));
      final encrypted = Encrypted(data);
      final decrypted = encrypter.decryptBytes(encrypted);
      return Uint8List.fromList(decrypted);
    } catch (e) {
      debugPrint('使用密钥引用解密错误: $e');
      return null;
    }
  }

  // ========== 别名方法（对应 OC 中的方法名） ==========

  /// 加密字符串（别名）
  static String? encryptString(String str, String key,
      {bool isPrivateKey = true}) {
    return isPrivateKey
        ? encryptStringWithPrivateKey(str, key)
        : encryptStringWithPublicKey(str, key);
  }

  /// 加密数据（别名）
  static Uint8List? encryptData(Uint8List data, String key,
      {bool isPrivateKey = true}) {
    return isPrivateKey
        ? encryptDataWithPrivateKey(data, key)
        : encryptDataWithPublicKey(data, key);
  }

  /// 签名字符串（别名）
  static String? signString(String str, String privateKey) {
    return signStringWithPrivateKey(str, privateKey);
  }

  /// 签名数据（别名）
  static Uint8List? signData(Uint8List data, String privateKey) {
    return signDataWithPrivateKey(data, privateKey);
  }

  /// 解密字符串（别名）
  static String? decryptString(String str, String key,
      {bool isPrivateKey = true}) {
    return isPrivateKey
        ? decryptStringWithPrivateKey(str, key)
        : decryptStringWithPublicKey(str, key);
  }

  /// 解密数据（别名）
  static Uint8List? decryptData(Uint8List data, String key,
      {bool isPrivateKey = true}) {
    return isPrivateKey
        ? decryptDataWithPrivateKey(data, key)
        : decryptDataWithPublicKey(data, key);
  }
}

/// 字符串扩展方法
extension RSAExtension on String {
  /// 使用公钥加密
  String? rsaEncryptWithPublicKey(String publicKeyPem) {
    return RSAUtil.encryptWithPublicKey(this, publicKeyPem);
  }

  /// 使用私钥解密
  String? rsaDecryptWithPrivateKey(String privateKeyPem) {
    // return RSAUtil.decryptWithPrivateKey(this, privateKeyPem);
    return RSAUtil.decryptString(this, privateKeyPem);
  }

  /// 使用私钥签名
  String? rsaSignWithPrivateKey(String privateKeyPem) {
    return RSAUtil.signWithPrivateKey(this, privateKeyPem);
  }

  /// 验证签名
  bool rsaVerifyWithPublicKey(String signature, String publicKeyPem) {
    return RSAUtil.verifyWithPublicKey(this, signature, publicKeyPem);
  }
}
